from rest_framework import status, viewsets, permissions, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.shortcuts import get_object_or_404
from django.db.models import Q, Avg

from .models import AgentType, Agent, AgentRating, Conversation, Message
from .serializers import (
    AgentTypeSerializer, AgentSerializer, AgentCreateSerializer, 
    AgentUpdateSerializer, AgentRatingSerializer, ConversationSerializer,
    ConversationCreateSerializer, MessageSerializer, ChatMessageSerializer
)
from .services import get_chat_service


class AgentTypeViewSet(viewsets.ReadOnlyModelViewSet):
    """智能体类型视图集"""
    queryset = AgentType.objects.all()
    serializer_class = AgentTypeSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]


class AgentViewSet(viewsets.ModelViewSet):
    """智能体视图集"""
    queryset = Agent.objects.all()
    serializer_class = AgentSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'agent_type', 'is_public', 'is_featured']
    search_fields = ['name', 'description', 'knowledge_domains']
    ordering_fields = ['created_at', 'updated_at', 'usage_count', 'rating']
    ordering = ['-created_at']
    
    def get_queryset(self):
        queryset = Agent.objects.all()
        
        # 根据权限过滤
        if self.action == 'list':
            # 只显示公开的智能体和用户自己创建的
            queryset = queryset.filter(
                Q(is_public=True) | Q(creator=self.request.user)
            )
        
        return queryset
    
    def get_serializer_class(self):
        if self.action == 'create':
            return AgentCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return AgentUpdateSerializer
        return AgentSerializer
    
    def perform_create(self, serializer):
        serializer.save(creator=self.request.user)
    
    def perform_update(self, serializer):
        # 只允许创建者更新
        if serializer.instance.creator != self.request.user and not self.request.user.is_staff:
            raise PermissionError("只有创建者可以更新智能体")
        serializer.save()
    
    def perform_destroy(self, instance):
        # 只允许创建者删除
        if instance.creator != self.request.user and not self.request.user.is_staff:
            raise PermissionError("只有创建者可以删除智能体")
        instance.delete()
    
    @action(detail=False, methods=['get'])
    def my_agents(self, request):
        """获取当前用户创建的智能体"""
        agents = Agent.objects.filter(creator=request.user)
        page = self.paginate_queryset(agents)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(agents, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def featured(self, request):
        """获取推荐智能体"""
        featured_agents = Agent.objects.filter(is_featured=True, is_public=True, status='active')
        page = self.paginate_queryset(featured_agents)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(featured_agents, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['post'])
    def rate(self, request, pk=None):
        """评分智能体"""
        agent = self.get_object()
        serializer = AgentRatingSerializer(data=request.data, context={'request': request})
        
        if serializer.is_valid():
            # 检查是否已经评分过
            existing_rating = AgentRating.objects.filter(agent=agent, user=request.user).first()
            if existing_rating:
                # 更新评分
                existing_rating.rating = serializer.validated_data['rating']
                existing_rating.comment = serializer.validated_data.get('comment', '')
                existing_rating.save()
                rating = existing_rating
            else:
                # 创建新评分
                rating = serializer.save(agent=agent, user=request.user)
            
            # 更新智能体的平均评分
            avg_rating = AgentRating.objects.filter(agent=agent).aggregate(Avg('rating'))['rating__avg']
            rating_count = AgentRating.objects.filter(agent=agent).count()
            agent.rating = round(avg_rating, 2) if avg_rating else 0
            agent.rating_count = rating_count
            agent.save()
            
            return Response(AgentRatingSerializer(rating).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['get'])
    def ratings(self, request, pk=None):
        """获取智能体的所有评分"""
        agent = self.get_object()
        ratings = AgentRating.objects.filter(agent=agent).order_by('-created_at')
        page = self.paginate_queryset(ratings)
        if page is not None:
            serializer = AgentRatingSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = AgentRatingSerializer(ratings, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['post'])
    def chat(self, request, pk=None):
        """与智能体对话"""
        agent = self.get_object()
        serializer = ChatMessageSerializer(data=request.data)
        
        if serializer.is_valid():
            message_text = serializer.validated_data['message']
            conversation_id = serializer.validated_data.get('conversation_id')
            
            # 获取或创建对话
            if conversation_id:
                conversation = get_object_or_404(
                    Conversation, 
                    id=conversation_id, 
                    user=request.user, 
                    agent=agent
                )
            else:
                conversation = Conversation.objects.create(
                    agent=agent,
                    user=request.user,
                    title=message_text[:50] + '...' if len(message_text) > 50 else message_text
                )
            
            # 保存用户消息
            user_message = Message.objects.create(
                conversation=conversation,
                role='user',
                content=message_text
            )
            
            # 使用AI服务生成回复
            chat_service = get_chat_service(agent)
            ai_response = chat_service.generate_response(conversation, message_text)
            
            # 保存AI回复
            ai_message = Message.objects.create(
                conversation=conversation,
                role='assistant',
                content=ai_response
            )
            
            # 更新智能体使用统计
            agent.update_usage()
            
            return Response({
                'conversation_id': conversation.id,
                'user_message': MessageSerializer(user_message).data,
                'ai_message': MessageSerializer(ai_message).data
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ConversationViewSet(viewsets.ModelViewSet):
    """对话视图集"""
    queryset = Conversation.objects.all()
    serializer_class = ConversationSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering = ['-updated_at']
    
    def get_queryset(self):
        return Conversation.objects.filter(user=self.request.user)
    
    def get_serializer_class(self):
        if self.action == 'create':
            return ConversationCreateSerializer
        return ConversationSerializer
    
    @action(detail=True, methods=['get'])
    def messages(self, request, pk=None):
        """获取对话的消息列表"""
        conversation = self.get_object()
        messages = conversation.messages.all().order_by('created_at')
        page = self.paginate_queryset(messages)
        if page is not None:
            serializer = MessageSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = MessageSerializer(messages, many=True)
        return Response(serializer.data)


class MessageViewSet(viewsets.ReadOnlyModelViewSet):
    """消息视图集"""
    queryset = Message.objects.all()
    serializer_class = MessageSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Message.objects.filter(conversation__user=self.request.user)